﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Globalization;

namespace ProjetoFinal.Resources
{
    static class CVUtils
    {

        public static string hexToBinary(string hexValue)
        {
            if (hexValue.Length == 0) return "";

            string binaryValue = "";
            binaryValue = Convert.ToString(Convert.ToInt64(hexValue, 16), 2);

            try
            {
                binaryValue = Convert.ToString(Convert.ToInt64(hexValue, 16), 2);
            }
            catch
            {
                return "Entrada não reconhecida.";
            }

            return binaryValue;
        }

        public static string binaryToHex(string binValue)
        {
            if (binValue.Length == 0) return "";
            string hexValue = "";
            try
            {
                hexValue = Convert.ToString(Convert.ToInt64(binValue, 2), 16);
            }
            catch 
            {
                return "Entrada não reconhecida.";
            }

            
            return hexValue;
        }
        /*
        public static byte[] StringToByteArray(string hex)
        {
            if (hex.Length % 2 == 1)
                throw new Exception("The binary key cannot have an odd number of digits");

            byte[] arr = new byte[hex.Length >> 1];

            for (int i = 0; i < hex.Length >> 1; ++i)
            {
                arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
            }

            return arr;
        } 
        */

        public static byte[] stringHexToByteArray(string hex)
        {
            if ((hex.Length % 2) != 0)
            {
                throw new ArgumentException("Invalid length: " + hex.Length);
            }

            if (hex.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
            {
                hex = hex.Substring(2);
            }

            int arrayLength = hex.Length / 2;
            byte[] byteArray = new byte[arrayLength];
            for (int i = 0; i < arrayLength; i++)
            {
                byteArray[i] = byte.Parse(hex.Substring(i * 2, 2), NumberStyles.HexNumber);
            }

            Console.WriteLine(byteArray.ToString());

            return byteArray;
        }

    }
}
